﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using Framework.Common;
using System.IO;
using Framework.Common.Exceptions;
using YouTravel.Framework;
using YouTravel.Framework.ResourceMessage;
using YouTravel.Framework.Const;

namespace Application.Upload.Handler
{
	/// <summary>
	/// UploadImages 的摘要说明
	/// </summary>
	public class UploadImages : IHttpHandler
	{
		static DateTime _date = DateTime.Now;
		static readonly string BasePath = AppDomain.CurrentDomain.BaseDirectory +"/";
		static readonly string Yearmonth = _date.ToString("yyyyMM");
	    readonly CommonGlobal _globalCommon = CommonGlobal.getInstance();
	    readonly CommonMD5 _commonMd5 = CommonMD5.getInstance();
		DataResult _dataResult = new DataResult();

		public void ProcessRequest(HttpContext context)
		{
			context.Response.ContentType = "application/json;charset=UTF-8";
			context.Response.AddHeader("Pragma", "no-cache");
			context.Response.AddHeader("Cache-Control", "private, no-cache");
			context.Response.Charset = "utf-8";
			context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
			try
			{
				string pwd = HttpContext.Current.Request["FilePwd"];//约定密钥

				if (string.IsNullOrEmpty(pwd))
				{
					throw new Exception(BusinessResourceMessage.NoPower);
				}
				else
				{
					string mpwd = _commonMd5.GetUploadMD5(_date);
					if (mpwd.Trim() == pwd.Trim())
					{
						//得到文件上传文件路径   
						HttpPostedFile file = HttpContext.Current.Request.Files["FileData"];
						context.Response.Write(_globalCommon.ReturnJsonToString((int)ResponseStatusCode.Success, BusinessResourceMessage.Success, UploadAattachment(file)));
						context.Response.End();						
					}
					else
					{
						throw new Exception(BusinessResourceMessage.NoPower);
					}
				}
			}
			catch (Exception Ex)
			{
				context.Response.Write(_globalCommon.ReturnJsonToString((int)ResponseStatusCode.Error, Ex.Message.ToString()));
				context.Response.End();
			}
		}

		/// <summary>
		/// 上传附件
		/// </summary>
		/// <param name="file"></param>
		private string UploadAattachment(HttpPostedFile file)
		{
			string path = ConfigurationManager.AppSettings["AattachmentPath"];
			string fileSize = ConfigurationManager.AppSettings["FileSize"];
			string pathFull = BasePath + path + Yearmonth;
			string fileEnd = file.FileName.Trim().Substring(file.FileName.Trim().LastIndexOf(".") + 1).ToLower();
			if (fileEnd == "gif" || fileEnd == "jpg" || fileEnd == "png" || fileEnd == "jpeg" || fileEnd == "bmp")
			{
				string head = DateTime.Now.ToString("yyyyMMddHHmmss");
				string fileName = head + "." + fileEnd;
				//如果不存在该目录，则创建目录
				if (!Directory.Exists(pathFull))
				{
					Directory.CreateDirectory(pathFull);
				}
				int iFileSize = 1;
				if (fileSize != null)
					iFileSize = int.Parse(fileSize);
				if (file.ContentLength > 0 && file.ContentLength <= (iFileSize * ConfigConst.FileSize))
				{
					try
					{
						string fpath = pathFull + "/" + fileName;
						file.SaveAs(fpath);
                        string rmsg = path + Yearmonth + "/" + fileName;
						return "\"" + rmsg + "\"";
					}
					catch {
						throw new Exception(string.Format(BusinessResourceMessage.FailMsg,"文件上传"));
					}
				}
				else
				{
					throw new Exception(BusinessResourceMessage.UploadFileSizeError);
				}
			}
			else
			{
				throw new Exception(BusinessResourceMessage.UploadFormatError);
			}
		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}